package com.gjh.xiaokabang2code.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gjh.xiaokabang2code.common.*;
import com.gjh.xiaokabang2code.mapper.SearchFinderMapper;
import com.gjh.xiaokabang2code.mapper.SearchLoserMapper;
import com.gjh.xiaokabang2code.model.SearchFinder;
import com.gjh.xiaokabang2code.model.SearchLoser;
import com.gjh.xiaokabang2code.model.request.MailRt;
import com.gjh.xiaokabang2code.model.response.LoginRs;
import com.gjh.xiaokabang2code.model.response.VerifyRs;
import com.gjh.xiaokabang2code.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import static com.gjh.xiaokabang2code.common.CustomMailSender.*;
import static com.gjh.xiaokabang2code.constant.UserConstant.USER_LOGIN_KEY;
import static com.gjh.xiaokabang2code.constant.UserConstant.USER_SAFETY_KEY;

@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class CommonServiceImpl implements CommonService {

    @Resource
    private SearchFinderMapper searchFinderMapper;

    @Resource
    private SearchLoserMapper searchLoserMapper;

    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    public static final String SALT = "XiaoKabang2Bygjh2003";

    @Override
    public ArrayList<String> loseList() throws Exception {
        QueryWrapper<SearchFinder> searchFinderQueryWrapper = new QueryWrapper<>();
        searchFinderQueryWrapper.eq("status", 0);
        List<SearchFinder> searchFinders = searchFinderMapper.selectList(searchFinderQueryWrapper);
        if (searchFinders.isEmpty()) {
            return null;
        }
        ArrayList<String> strings = new ArrayList<>();
        for (SearchFinder searchFinder : searchFinders) {
            strings.add("尾号" + HideCharactersUtil.convertToFourDigits(new DesUtil(SALT).decrypt(searchFinder.getUBankcard(), "CBC")) + "的校园卡丢失,求帮助");
        }
        return strings;
    }

    @Override
    public ArrayList<String> findList() throws Exception {
        QueryWrapper<SearchLoser> searchLoserQueryWrapper = new QueryWrapper<>();
        searchLoserQueryWrapper.eq("status", 0);
        List<SearchLoser> searchLosers = searchLoserMapper.selectList(searchLoserQueryWrapper);
        if (searchLosers.isEmpty()) {
            return null;
        }
        ArrayList<String> strings = new ArrayList<>();
        for (SearchLoser searchLoser : searchLosers) {
            strings.add("捡到尾号" + HideCharactersUtil.convertToFourDigits(new DesUtil(SALT).decrypt(searchLoser.getUBankcard(), "CBC")) + "的校园卡,失主尽快联系");
        }
        return strings;
    }

    @Override
    public Boolean sendSafetyCode(LoginRs loginUser) {
        String uId = loginUser.getUId();
        if (uId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "uId为空");
        }
        if(!uId.equals(loginUser.getUId())){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "系统内部严重错误");
        }
//        String stuNumMail = "vm" + uId + "@jzxy.edu.cn";
        //如果redis缓存中有，直接读缓存
        String redisKey = String.format("xkb:safetyCode:recommend:%s",uId);
        String verifyCode = (String)redisTemplate.opsForValue().get(redisKey);
        if(verifyCode!=null){
            SafetyCheckMailSendNext("tsin09@qq.com",verifyCode);
            return true;
        }
        //没有就写入缓存
        try {
            String stuNumMail = "vm" + uId + "@jzxy.edu.cn";
            verifyCode = SafetyCheckMailSend(stuNumMail);
            redisTemplate.opsForValue().set(redisKey,verifyCode,600, TimeUnit.SECONDS);
        } catch (Exception e) {
            log.error("redis缓存数据发生错误", e);
        }
        return true;
    }

    @Override
    public String verifySafetyCode(String verifyCode, HttpServletRequest httpServletRequest) {
        LoginRs loginUser = HttpSessionUtil.getLoginUser(httpServletRequest);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN, "未登录无法正常使用当前页面功能");
        }
        String uId = loginUser.getUId();
        if (uId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "uId为空");
        }
        //纯数字
        boolean matches = Pattern.matches("\\d+", verifyCode);
        if (!matches) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "学号包含除数字外符号（S1001）");
        }
        //10位
        if (verifyCode.length() != 6) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "学号长度不是6位（S1002）");
        }
        String redisKey = String.format("xkb:safetyCode:recommend:%s",uId);
        String verifyCodeT = (String)redisTemplate.opsForValue().get(redisKey);
        if(verifyCodeT==null){
            throw new BusinessException(ErrorCode.DATA_NULL, "返回数据为空（C1002）");
        }
        if(!verifyCodeT.equals(verifyCode)){
            throw new BusinessException(ErrorCode.DATA_NULL, "返回数据为空（C1002）");
        }
        //记录登录状态
        VerifyRs verifyRs = new VerifyRs();
        verifyRs.setUc(loginUser.getUc());
        verifyRs.setUId(loginUser.getUId());
        httpServletRequest.getSession().setAttribute(USER_SAFETY_KEY, verifyRs);
        return verifyRs.getUc();
    }
}
